import { reqCartList,reqCheckCart,reqDeleteCart } from '../../api';
const actions = {
  // 获取购物车数据
  async getCartList({commit}){
    let result = await reqCartList()
    if(result.code === 200){
      commit('GETCAERLIST',result.data)
    }
  },
  // 获取复选框接口
  async getCheckCart({commit},{skuId,isChecked}){
    let result = await reqCheckCart(skuId,isChecked)
    // console.log(skuId,isChecked)
    if(result.code === 200){
      return "ok"
    }else{
      return Promise.reject(new Error('getCheckCart: baocuole'))
    }
  },
  // 获取复选框全选按钮数据
  changeAllCheck({dispatch,getters},isAllChecked){
    let promiseAll = []
    getters.cartInfoList.cartInfoList.forEach(item => {
      // item.isChecked = isAllChecked
      let promise = dispatch('getCheckCart',{skuId:item.skuId,isChecked:isAllChecked})
      promiseAll.push(promise)
    })
    // 最终返回结果
    return Promise.all(promiseAll)
  },
  // 获取删除购物车商品数据
  async getDeleteCartById({commit},stuId){
    let result = await reqDeleteCart(stuId) 
    if(result.code === 200){
      return "ok"
    }else{
      return Promise.reject(new Error('getDeleteCartById:baocuole'))
    }
  },
  // 获取删除所有选中的商品数据
  deleteAllCheckedCart({dispatch,getters}){
    let promiseAll = []
    // vuex 调用 vuex 里面的数据方法
    getters.cartInfoList.cartInfoList.forEach(item => {
      let promise = '';
      if(item.isChecked === 1){
        promise = dispatch('getDeleteCartById',item.skuId)
      }else{
        promise = ''
      }
      // let promise = item.isChecked === 1 ? dispatch('getDeleteCartById',item.skuId) : ''
      // console.log(promise)
      promiseAll.push(promise)
      
    })
    // Promise.all([p1,p2,p3...]) 当 里面的值都是成功的时候 则成功 如有一个是失败的 则是失败
    return Promise.all(promiseAll)
  }
  
}
const mutations = {
  GETCAERLIST(state,data){
    state.cartInfoList = data
  }
}
const state = {
  cartInfoList:[]
}
const getters = {
  cartInfoList(state){
    return state.cartInfoList[0] || []
  }
}
export default{
  namespaced:true,
  actions,
  mutations,
  state,
  getters
}